﻿using BCData.Sim.Admin.AdminSpecificPermission;
using BCData.Sim.Admin.AdminSpecificPermissionRecord;
using BCDto.Sim.Admin.AdminSpecificPermissionRecord;
using BCEntity.Sim.Admin.AdminSpecificPermissionRecord;
using BCService.Utils;
using System;
using System.Collections.Generic;

namespace BCService.Sim.Admin.AdminSpecificPermissionRecordService
{
    public class AdminSpecificPermissionRecordService: IAdminSpecificPermissionRecordService
    {
        private readonly IAdminSpecificPermissionData adminSpecificPermissionData;
        private readonly IAdminSpecificPermissionRecordData adminSpecificPermissionRecordData;

        public AdminSpecificPermissionRecordService(IAdminSpecificPermissionData adminSpecificPermissionData,
            IAdminSpecificPermissionRecordData adminSpecificPermissionRecordData)
        {
            this.adminSpecificPermissionData = adminSpecificPermissionData;
            this.adminSpecificPermissionRecordData = adminSpecificPermissionRecordData;
        }

        public AdminSpecificPermissionRecordDto Add(AdminSpecificPermissionRecordRequestDto adminSpecificPermissionRecordRequestDto)
        {
            var adminSpecificPermissionEntity = this.adminSpecificPermissionData.Get(adminSpecificPermissionRecordRequestDto.SpecificPermissionKey).GetAwaiter().GetResult();

            if (adminSpecificPermissionEntity == null)
            {
                throw new ArgumentException("此特殊权限不存在");
            }

            if (this.CheckExists(adminSpecificPermissionRecordRequestDto.AdminId, adminSpecificPermissionEntity.SpecificPermissionKey))
            {
                throw new ArgumentException("此管理员已存此权限，无须重复设置");
            }

            AdminSpecificPermissionRecordEntity entity = new AdminSpecificPermissionRecordEntity
            {
                AdminId = adminSpecificPermissionRecordRequestDto.AdminId,
                SpecificPermissionName = adminSpecificPermissionEntity.SpecificPermissionName,
                SpecificPermissionKey = adminSpecificPermissionEntity.SpecificPermissionKey
            };

            return this.adminSpecificPermissionRecordData.Add(entity).GetAwaiter().GetResult().As<AdminSpecificPermissionRecordDto>();
        }

        public bool CheckExists(long adminId, string extensionPermissionKey)
        {
            return this.adminSpecificPermissionRecordData.CheckExists(adminId, extensionPermissionKey).GetAwaiter().GetResult();
        }

        public void Delete(long adminId,string extensionPermissionKey)
        {
            this.adminSpecificPermissionRecordData.Delete(adminId,extensionPermissionKey);
        }

        public IEnumerable<AdminSpecificPermissionRecordDto> Query(long adminId)
        {
            return this.adminSpecificPermissionRecordData.Query(adminId).GetAwaiter().GetResult().As<IEnumerable<AdminSpecificPermissionRecordDto>>();
        }
    }
}
